package tech.mhuang.ext.jwt.sample;

import tech.mhuang.ext.jwt.admin.JwtBuilder;
import tech.mhuang.ext.jwt.admin.JwtFramework;
import tech.mhuang.ext.jwt.admin.bean.Jwt;
import tech.mhuang.ext.jwt.admin.bean.JwtConsts;
import tech.mhuang.ext.jwt.admin.external.IJwtExternal;
import tech.mhuang.ext.jwt.admin.external.IJwtProducer;

import java.util.HashMap;
import java.util.Map;

/**
 * jwt测试
 *
 * @author mhuang
 * @since 1.0.0
 */
public class JwtSampleTest {

    public static void main(String[] args) {
        //获取Jwt构造器
        JwtBuilder.Builder builder = JwtBuilder.builder();

        //创建可使用的jwt 2个对象、第一个过期1分钟、2个默认的30天
        Jwt.JwtBean bean1 =  builder.createProducerBuilder().clientId(JwtConsts.DEFAULT_CLIENT_ID)
                .expireMinute(1L) //1分钟
                .headerName(JwtConsts.DEFAULT_HEADER_NAME)
                .name(JwtConsts.DEFAULT_NAME)
                .type(JwtConsts.DEFAULT_TYPE)
                .secret(JwtConsts.DEFAULT_SECRET).builder();

        Jwt.JwtBean bean2 =  builder.createProducerBuilder().builder();
        //构建2个jwt对象
        JwtFramework framework = builder.bindProducer("1",bean1).bindProducer("2",bean2).builder();
        //启动Jwt
        framework.start();
        //获取平台中的key1的Jwt生产者
        IJwtProducer producer = framework.getProducer("1");
        //创建生产Token额外需要的参数
        Map<String,Object> map = new HashMap<>();
        map.put("userId","1");
        //Token创建
        String token = producer.create(map);
        //刷新Token
        String refreshToken = producer.refresh(map);
        //解析Token
        Map<String,Object> map2 = producer.parse(token);

        System.out.println(map2);
        System.out.println(producer.parse(refreshToken));

        //修改Jwt成自定义实现
        framework.external(new CustomJwtExt()).start();
        framework.getProducer("1").create(map);
    }

    /**
     * 自定义Token实现
     */
    static class CustomJwtExt implements IJwtExternal{
        @Override
        public IJwtProducer create(String key) {
            return new CustomJwtProducer();
        }
    }

    /**
     * 自定义JWT解析方式
     */
    static class CustomJwtProducer implements IJwtProducer{

        private Jwt.JwtBean jwt;

        @Override
        public void add(Jwt.JwtBean jwt) {
            System.out.println("设置了JWT属性");
            this.jwt = jwt;
        }

        @Override
        public void name(String name) {
            System.out.println("打印key"+name);
        }

        @Override
        public Map<String, Object> parse(String jsonWebToken) {
            System.out.println("解析了Token");
            return null;
        }

        @Override
        public String refresh(Map<String, Object> claims) {
            System.out.println("刷新了Token");
            return null;
        }

        @Override
        public String create(Map<String, Object> claims) {
            System.out.println("创建了Token");
            return null;
        }
    }
}
